<?php

error_reporting(E_ALL);
ini_set("display_errors", "on");
define("DS", DIRECTORY_SEPARATOR);
define("SITE_PATH", implode(DS, array(realpath(dirname(__FILE__)))));

function autoload($className)
{
	$path = implode(DS, array(SITE_PATH, "library", sprintf("%s.php", str_replace("_", DIRECTORY_SEPARATOR, $className))));
	if (file_exists($path))
	{
		include($path);
	}
}
spl_autoload_register("autoload");

function exception_handler(Exception $e)
{
	printf("<p>Message: %s", $e->getMessage());
	echo "<ol>";
	$exceptionList = array($e);
	while (method_exists($e, "getPrevious") && $e = $e->getPrevious())
	{
		$exceptionList[] = $e;
	}
	$exceptionList = array_reverse($exceptionList);
	foreach ($exceptionList as $e)
	{
		printf("<li>%s<br />%s:%s</li>", get_class($e), $e->getFile(), $e->getLine());
	}
	echo "</ol>";
	global $template;
	printf("<pre>%s</pre>", print_r($template->getTemplateList(), true));
}
set_exception_handler("exception_handler");

define("DEFAULT_PAGE", "home");
$validPages = array("hello", "user/view");
$page = DEFAULT_PAGE;
if (!empty($_GET) && array_key_exists("page", $_GET))
{
	$providedPage = $_GET["page"];
	if (in_array($providedPage, $validPages))
	{
		$page = $providedPage;
	}
}

$templateDirectory = implode(DS, array(SITE_PATH, "templates"));
$variableList = array("username" => "Adrian", "user" => array());
$template = new Template($templateDirectory, $variableList);
try
{
	echo $template->initialise(Template::RETURN_RENDERING, $page);
}
catch (Template_Exception $e)
{
	throw new System_Exception($e->getMessage(), 0, $e);
}